from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from typing import List, Optional
from sqlalchemy.orm import Session
from database import get_db
from crud import get_landmarks, get_landmark, create_landmark, update_landmark, delete_landmark
from models import Landmark as LandmarkModel
from auth import get_current_active_user
from datetime import datetime

router = APIRouter(prefix="/api/landmarks", tags=["landmarks"])

# 数据模型
class Landmark(BaseModel):
    id: Optional[int] = None
    name: str
    lat: float
    lng: float
    summary: str
    details: str
    media: List[str] = []
    time: Optional[datetime] = None

# API路由 - 地标相关
@router.get("/", response_model=List[Landmark])
async def get_landmarks_route(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取所有地标"""
    # 此接口为公开访问，不需要认证
    landmarks = get_landmarks(db, skip=skip, limit=limit)
    result = []
    for landmark in landmarks:
        result.append(Landmark(
            id=landmark.id,
            name=landmark.name,
            lat=landmark.lat,
            lng=landmark.lng,
            summary=landmark.summary,
            details=landmark.details,
            media=landmark.media,
            time=landmark.time
        ))
    return result

@router.get("/{id}", response_model=Landmark)
async def get_landmark_route(request: Request, id: int, db: Session = Depends(get_db)):
    """获取指定地标"""
    # 此接口为公开访问，不需要认证
    landmark = get_landmark(db, landmark_id=id)
    if not landmark:
        raise HTTPException(status_code=404, detail="地标未找到")

    return Landmark(
        id=landmark.id,
        name=landmark.name,
        lat=landmark.lat,
        lng=landmark.lng,
        summary=landmark.summary,
        details=landmark.details,
        media=landmark.media,
        time=landmark.time
    )

@router.post("/", response_model=Landmark)
async def create_landmark_route(request: Request, landmark: Landmark, db: Session = Depends(get_db)):
    """创建新地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    db_landmark = create_landmark(
        db=db,
        name=landmark.name,
        lat=landmark.lat,
        lng=landmark.lng,
        summary=landmark.summary,
        details=landmark.details,
        creator_id=current_user.id,
        media=landmark.media,
        time=landmark.time
    )

    return Landmark(
        id=db_landmark.id,
        name=db_landmark.name,
        lat=db_landmark.lat,
        lng=db_landmark.lng,
        summary=db_landmark.summary,
        details=db_landmark.details,
        media=db_landmark.media,
        time=db_landmark.time
    )

@router.put("/{id}", response_model=Landmark)
async def update_landmark_route(request: Request, id: int, landmark: Landmark, db: Session = Depends(get_db)):
    """更新地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    db_landmark = update_landmark(
        db=db,
        landmark_id=id,
        name=landmark.name,
        lat=landmark.lat,
        lng=landmark.lng,
        summary=landmark.summary,
        details=landmark.details,
        media=landmark.media,
        time=landmark.time
    )

    if not db_landmark:
        raise HTTPException(status_code=404, detail="地标未找到")

    return Landmark(
        id=db_landmark.id,
        name=db_landmark.name,
        lat=db_landmark.lat,
        lng=db_landmark.lng,
        summary=db_landmark.summary,
        details=db_landmark.details,
        media=db_landmark.media,
        time=db_landmark.time
    )

@router.delete("/{id}")
async def delete_landmark_route(request: Request, id: int, db: Session = Depends(get_db)):
    """删除地标"""
    # 从中间件获取当前用户
    current_user = getattr(request.state, 'user', None)
    if not current_user:
        raise HTTPException(status_code=401, detail="未授权访问")

    success = delete_landmark(db, landmark_id=id)
    if not success:
        raise HTTPException(status_code=404, detail="地标未找到")

    return {"message": "地标已删除"}
